import apiUrl from './apiUrl';
import {Utils} from './utils/Utils';

function buildApiCall(url){
    return function(data){
        let formData = Utils.getFormData(data);
        return fetch(url, {
            method: 'POST',
            body: formData,
            credentials: 'include',
            cache: 'no-cache',
        }).then(res => {
            if(res.ok){
                try {
                    return res.json();
                } catch(e){
                    return {status: 0, msg: [['error', 'ERR::NETWORK', '网络错误', '服务器返回的数据不正确']]}
                }
            } else {
                return {status: 0, msg: [['error', 'ERR::NETWORK', '网络错误', res.status + ' ' + res.statusText]]}
            }
        });
    }
}

export default new Proxy(apiUrl, {
    get: function(target, key){
        if(target[key]){
            return buildApiCall(target[key]);
        } else {
            return null;
        }
    },
});